package oop.lab.console.playground;

import java.util.ArrayList;
import java.util.List;

import oop.lab.console.command.Command;
import oop.lab.console.gameview.GameViewer;
import oop.lab.console.gameview.GomokuGameView;
import oop.lab.console.gameview.PeaceGameView;
import oop.lab.console.gameview.ReversiGameView;
import oop.lab.domain.board.PieceColor;
import oop.lab.domain.game.GameException;

public class PlayGround {

    private final Player player1;
    private final Player player2;
    private final List<GameViewer> games = new ArrayList<>();
    private int currentGame = 0;
    // 最后一次用户输入发生的错误
    private String lastErrorMessage;

    public PlayGround(Player player1, Player player2) {
        this.player1 = player1;
        this.player2 = player2;
        // Initialize default games
        games.add(PeaceGameView.create());
        games.add(PeaceGameView.createWithFinishState());
        games.add(ReversiGameView.create());
        games.add(ReversiGameView.createWithFinalState());
        games.add(GomokuGameView.create());
    }

    public Player getPlayer1() {
        return player1;
    }

    public Player getPlayer2() {
        return player2;
    }

    public Player getPlayer(PieceColor color) {
        if (color == player1.getPieceColor()) {
            return player1;
        } else {
            return player2;
        }
    }

    public void activateGame(int index) {
        if (index < 0 || index >= games.size()) {
            throw new GameException(String.format("游戏编号应该在1~%d之间", games.size()));
        }
        currentGame = index;
    }

    public List<GameViewer> getGames() {
        return games;
    }

    public void addGame(GameViewer gameViewer) {
        games.add(gameViewer);
    }

    public GameViewer getCurrentGameViewer() {
        return games.get(currentGame);
    }

    public String getLastErrorMessage() {
        return lastErrorMessage;
    }

    public void setLastErrorMessage(String message) {
        this.lastErrorMessage = message;
    }

    public void clearLastErrorMessage() {
        this.lastErrorMessage = null;
    }

    public void executeCommand(String input) {
        GameViewer gameViewer = getCurrentGameViewer();
        List<Command> commands = gameViewer.getCommandList(this); // Pass PlayGround instead of PlayGroundVIew
        for (Command command : commands) {
            if (command.isEnabled() && command.canAccept(input)) {
                command.execute(input);
                clearLastErrorMessage(); // Clear error on successful execution
                return;
            }
        }
        throw new GameException("未识别的或当前无效的命令:" + input);
    }
}